package interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import entity.SysUser;

public class AuthInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(AuthInterceptor.class);
    public boolean preHandle(HttpServletRequest request, HttpServletResponse
            response,
                             Object handler) throws Exception {
        LOGGER.debug("进入自定义拦截器 AuthInterceptor，请求路径:{}",
                request.getRequestURI());
        HttpSession session = request.getSession();
        // 获取登录用户
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        // 验证登录状态
        if (null == sysUser) {
            // 没有登录信息， 跳转到 401.jsp 错误页
            request.getRequestDispatcher("/WEB-INF/jsp/401.jsp")
                    .forward(request, response);
            // 返回 false 表示请求被拒绝，在返回之前需要做其他响应操作。
            return false;
        }
        // 返回 true 表示请求可以通过
        return true;
    }

}
